package com.gimi.cloud.jimi.common.utils;

import com.google.gson.Gson;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;


public class HttpPostDataUtil {

	public static Map PostData (String url , Object head , Object body) {
		Gson gson = new Gson();
		Map<String, Object> param = new HashMap<>();
		param.put("head", head);
		param.put("body", body);
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost post = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).build();//设置请求和传输超时时间
		post.setConfig(requestConfig);
		post.setHeader("Content-Encoding", "utf-8");
		post.setHeader("content-type", "application/json");

		StringEntity entity = new StringEntity(gson.toJson(param), Charset.forName("UTF-8"));
		System.out.println(gson.toJson(param));
		entity.setContentEncoding("UTF-8");
		//发送Json格式的数据请求
		entity.setContentType("application/json");
		Map resultMap = new HashMap();
		post.setEntity(entity);
		try {
			Map<String, String> map = new HashMap<>();
			HttpResponse response = httpclient.execute(post);
			HttpEntity httpEntity = response.getEntity();
			String rs = EntityUtils.toString(httpEntity, "UTF-8");
			HashMap<String, ?> resultJson = gson.fromJson(rs, HashMap.class);
			if(resultJson.get("ret_code").toString().equals("0000")){
				resultMap.put("msg" , resultJson.get("ret_msg").toString());
				resultMap.put("code", 0);
			}else {
				resultMap.put("msg" , resultJson.get("ret_msg").toString());
				resultMap.put("code", 1);
			}
			return resultMap;
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("msg" , e.getMessage());
			resultMap.put("code", 1);
			return resultMap;
		} finally {
			if (post != null) {
				post.releaseConnection();
			}
		}
	}
}
